from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.models import Sample, MarkerAnalysis
from app import db
from datetime import datetime

bp = Blueprint('analysis', __name__, url_prefix='/analysis')

@bp.route('/')
@login_required
def index():
    # 获取当前用户的样品和分析数据
    samples = Sample.query.filter_by(user_id=current_user.id).all()
    analyses = MarkerAnalysis.query.filter_by(user_id=current_user.id).order_by(MarkerAnalysis.analysis_date.desc()).all()
    return render_template('analysis/index.html', samples=samples, analyses=analyses)

@bp.route('/add', methods=['POST'])
@login_required
def add():
    try:
        # 获取表单数据
        sample_id = request.form.get('sample_id')
        pina_type = request.form.get('pina_type')
        pinb_type = request.form.get('pinb_type')
        sequence_data = request.form.get('sequence_data')
        notes = request.form.get('notes')

        # 验证样品存在且属于当前用户
        sample = Sample.query.get_or_404(sample_id)
        if sample.user_id != current_user.id:
            flash('无权访问此样品', 'danger')
            return redirect(url_for('analysis.index'))

        # 根据Pina和Pinb基因类型判断籽粒硬度
        grain_hardness = determine_grain_hardness(pina_type, pinb_type)

        # 创建分析记录
        analysis = MarkerAnalysis(
            sample_id=sample_id,
            pina_type=pina_type,
            pinb_type=pinb_type,
            grain_hardness=grain_hardness,
            sequence_data=sequence_data,
            notes=notes,
            user_id=current_user.id
        )

        db.session.add(analysis)
        db.session.commit()
        flash('分析数据添加成功', 'success')

    except Exception as e:
        db.session.rollback()
        flash(f'添加失败：{str(e)}', 'danger')

    return redirect(url_for('analysis.index'))

@bp.route('/edit/<int:id>', methods=['POST'])
@login_required
def edit(id):
    analysis = MarkerAnalysis.query.get_or_404(id)
    
    # 确保只能编辑自己的数据
    if analysis.user_id != current_user.id:
        flash('无权编辑此数据', 'danger')
        return redirect(url_for('analysis.index'))
    
    try:
        analysis.pina_type = request.form['pina_type']
        analysis.pinb_type = request.form['pinb_type']
        analysis.grain_hardness = determine_grain_hardness(
            request.form['pina_type'], 
            request.form['pinb_type']
        )
        analysis.sequence_data = request.form['sequence_data']
        analysis.notes = request.form['notes']
        
        db.session.commit()
        flash('分析数据更新成功', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'更新失败：{str(e)}', 'danger')
    
    return redirect(url_for('analysis.index'))

@bp.route('/delete/<int:id>', methods=['POST'])
@login_required
def delete(id):
    analysis = MarkerAnalysis.query.get_or_404(id)
    
    if analysis.user_id != current_user.id:
        flash('无权删除此数据', 'danger')
        return redirect(url_for('analysis.index'))
    
    try:
        db.session.delete(analysis)
        db.session.commit()
        flash('分析数据删除成功', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败：{str(e)}', 'danger')
    
    return redirect(url_for('analysis.index'))

def determine_grain_hardness(pina_type, pinb_type):
    """根据Pina和Pinb基因类型判断籽粒硬度"""
    if pina_type == 'wild' and pinb_type == 'wild':
        return 'soft'  # 软质
    elif pina_type == 'null' or pinb_type == 'null':
        return 'hard'  # 硬质
    elif pina_type == 'mutation' or pinb_type == 'mutation':
        return 'medium'  # 中等
    else:
        return 'unknown'  # 未知
